package br.com.tgalas.sistema.util;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.SessionFactory;

import br.com.tgalas.sistema.vendas.HibernateUtil;

public class ConexaoHibernateFilter implements Filter{
	private SessionFactory sF;
	
	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest servletReq, ServletResponse servletRes,
			FilterChain filter) throws IOException, ServletException {
		try {
			sF.getCurrentSession().beginTransaction();
			
		filter.doFilter(servletReq, servletRes);
		sF.getCurrentSession().getTransaction().commit();
		sF.getCurrentSession().close();
		System.out.println("...Encerrado");
		} catch (Throwable e) {
			try {
				if(sF.getCurrentSession().getTransaction().isActive()){
					sF.getCurrentSession().getTransaction().rollback();
				}
			} catch (Throwable e2) {
					e2.printStackTrace();
			}
			throw new ServletException();
		}
		
	}

	@Override
	public void init(FilterConfig conf) throws ServletException {
		sF = HibernateUtil.getSession();
		System.out.println("Iniciando...");
	}

}
